/*
 * @Author: Rays77
 * @Date: 2022-10-13 15:55:47
 * @LastEditors: yangrui63 yangrui63@gdii-yueyun.com
 * @LastEditTime: 2022-10-31 13:51:39
 * @Description:
 * @FilePath: \shop-admin\src\store\tabsStore\index.ts
 */

import { globalConfig } from '@/config/index'
import storage from '@/utils/localStorage'

/**
 * @description tabs的option属性
 * @param path 路由地址 {string}
 * @param title tab显示名称 {string}
 */
export interface ITabsOption {
  path: string
  title: string
}

export const useTabStore = defineStore('tabStore', () => {
  // state
  const activeIndex = ref('')
  const activeTitle = ref('')
  const options = ref([
    {
      path: '/',
      title: '首页',
    },
  ] as Array<ITabsOption>)

  // getter
  // const getOptions = computed(() => options);

  // action
  /**
   * @description 添加tabs
   * @param {ITabsOption} data
   */
  function add_tabs(data: ITabsOption) {
    options.value.push(data)
    set_active_item(data)
  }
  /**
   * @description 删除tabs
   * @param  {string} path 路由地址
   */
  function del_tabs(path: string) {
    let index = 0
    for (const option of options.value) {
      if (option.path === path) {
        break
      }
      index++
    }
    options.value.splice(index, 1) // 删除options里面下标为Index的一个数
  }
  /**
   * @description: 设置当前激活的tab
   * @param  {string} index 当前激动tab索引
   */
  function set_active_index(index: string) {
    activeIndex.value = index
  }
  /**
   * @description:设置tab页显示标题
   * @param {string} value
   */
  function set_title(value: string) {
    activeTitle.value = value
  }

  function set_active_item(item: ITabsOption) {
    activeTitle.value = item.title
    activeIndex.value = item.path
    storage.set(globalConfig.cache_current_tab, JSON.stringify(item))
  }

  return {
    activeIndex,
    activeTitle,
    options,
    add_tabs,
    del_tabs,
    set_active_index,
    set_title,
    set_active_item,
  }
})
